package com.sxhuayuan.parking.compenent.alipay;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.sxhuayuan.parking.entity.OemConfig;

@Component("alipayClient")
public class AlipayMultiAppClient implements IAlipayMultiAppClient {

	@Value("${alipay.serverUrl}")
	String alipayServerUrl;
	@Value("${alipay.format}")
	String alipayFormat;
	@Value("${alipay.charset}")
	String alipayCharset;
	@Value("${alipay.signType}")
	String alipaySignType;

	private Map<String, AlipayClient> clients = new HashMap<>();

	@Override
	public <T extends AlipayResponse> T execute(OemConfig oem, AlipayRequest<T> request) throws AlipayApiException {
		return getClient(oem).execute(request);
	}

	@Override
	public <T extends AlipayResponse> T execute(OemConfig oem, AlipayRequest<T> request, String authToken) throws AlipayApiException {
		return getClient(oem).execute(request, authToken);
	}

	@Override
	public <T extends AlipayResponse> T execute(OemConfig oem, AlipayRequest<T> request, String accessToken, String appAuthToken) throws AlipayApiException {
		return getClient(oem).execute(request, accessToken, appAuthToken);
	}

	@Override
	public <T extends AlipayResponse> T pageExecute(OemConfig oem, AlipayRequest<T> request) throws AlipayApiException {
		return getClient(oem).pageExecute(request);
	}

	@Override
	public <T extends AlipayResponse> T sdkExecute(OemConfig oem, AlipayRequest<T> request) throws AlipayApiException {
		return getClient(oem).sdkExecute(request);
	}

	@Override
	public <T extends AlipayResponse> T pageExecute(OemConfig oem, AlipayRequest<T> request, String method) throws AlipayApiException {
		return getClient(oem).pageExecute(request, method);
	}

	@Override
	public <TR extends AlipayResponse, T extends AlipayRequest<TR>> TR parseAppSyncResult(OemConfig oem, Map<String, String> result, Class<T> requsetClazz) throws AlipayApiException {
		return getClient(oem).parseAppSyncResult(result, requsetClazz);
	}

	private synchronized AlipayClient getClient(OemConfig oem) {
		String appid = oem.getAlipayAppid();
		if (clients.containsKey(appid)) {
			return clients.get(appid);
		}
		DefaultAlipayClient client = new DefaultAlipayClient(alipayServerUrl, appid, oem.getAlipayPriKey(), alipayFormat, alipayCharset, oem.getAlipayPubKey(), alipaySignType);
		clients.put(appid, client);
		return client;
	}

}
